package JavaSE.ReflectLearning.ChangeField;

import java.lang.reflect.Field;

/**
 *  学习 通过一个方法setAll，传入指定对象、变量名、新值，修改对象的某个值
 */
public class Demo {
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        Person person = new Person("张三", 14);
        System.out.println("修改前："+person);
        setAll(person, "name", "李四");
        setAll(person, "age", 36);
        System.out.println("修改后："+person);

    }
    public static void setAll(Object targetObj, String fieldName, Object newValue) throws IllegalAccessException, NoSuchFieldException {
        // 获取该对象的Class字节码文件对象
        Class targetClass = targetObj.getClass();
        // 获取Class对象的指定变量
        Field targetField = targetClass.getDeclaredField(fieldName);
        // 更改变量的访问权限
        targetField.setAccessible(true);
        // 输出变量名确认
        System.out.println("修改了变量 " + targetField.getName() + " -- " + targetField.get(targetObj));
        // 通过Field对象的set方法更改指定对象的值
        targetField.set(targetObj, newValue);
    }
}

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}